import React, { useEffect, useState } from 'react'
import { List, Toast, NavBar, Icon } from 'antd-mobile'
import getCountryPicker from '../../api/getCountryPicker'
import './index.less'
const Item = List.Item
export default function CountryPicker(props) {
    let [countryPicker, setCountryPicker] = useState({})
    useEffect(()=>{
        async function getData () {
            try {
                let res = await getCountryPicker()
                console.log(res.data.data)
                setCountryPicker(res.data.data)
            } catch {
                Toast.fail('数据请求失败！')
            }
        }
        getData()
    }, [])
    // 把对象的CountryPicker的key提取出来
    let countryPickerKeys = Object.keys(countryPicker)
    console.log(countryPickerKeys)
// 点击ul列表移动事件
const hendleScroll=(value)=>{
    return ()=>{
        window.scrollTo(0,document.getElementById(value).offsetTop-45)
    }
}
// 点击item返回数据，调回页面
let {history}=props
const goBack=(value)=>{
    return ()=>{
        history.push('./register/phone',value)
    }
}
    return (
        <div>
            <NavBar
            className='country-navBer'
                mode="light"
                icon={<Icon type="left" className="icon-left" />}
                onLeftClick={() => {}}
                
            >
                选择国家或者地区
            </NavBar>
            <div className='coutry-content'>
            {countryPickerKeys.map((countryKey, index) => {
                let countryPickerValue = countryPicker[countryKey]
                console.log(countryPickerValue, 'value')
                
                return (
                    <List className='country-list' id={countryKey} renderHeader={() => countryKey} key={index}>
                        {countryPickerValue.map((country) => {
                            console.log(country, 'country')
                            // country是一个对象
                            let keys = Object.keys(country)[0]
                            let value = country[keys]
                            return (
                                <Item 
                                className='country-item' extra={value} key={value} onClick={goBack(value)}>
                                    {keys}
                                </Item>
                            )
                        })}
                    </List>
                )
            })}
            <ul className='country-ul'>
                {countryPickerKeys.map(key=>{
                    return <li key={key} onClick={hendleScroll(key)}>{key}</li>
                })}
            </ul>
            </div>
        </div>
    )
}
